<template>
  <a-row :gutter="16" type="flex">
    <a-col :span="6">
      <a-card :bordered="false">
        <a-steps direction="vertical" v-model="current">
          <a-step disabled title="选择比对类型" description="选择需要比对的类型" />
          <a-step disabled title="上传文件" description="上传需要的文件" />
          <a-step disabled title="开始比对" description="内容开始比对" />
          <a-step disabled title="获取结果" description="已经完成了" />
        </a-steps>
      </a-card>
    </a-col>
    <a-col :span="18">
      <a-card :bordered="false">
        <div v-if="current === 0" class="a-flex a-flex-column a-col-center a-row-center type-card-list">
          <div class="a-flex">
            <div
              class="m-b-24 m-r-24 type-card large"
              :style="{ backgroundColor: item.backgroundColor }"
              v-for="(item, index) in cardList[0]"
              :key="index"
              @click="handleCardClick(item.text)"
            >
              <div class="text-left p-t-16 p-l-16">
                <a-icon :type="item.icon" class="fz-70" />
              </div>
              <p class="fz-20 m-t-30">{{ item.text }}</p>
            </div>
          </div>
          <div class="a-flex">
            <div
              class="m-b-24 m-r-24 type-card default a-flex a-row-center a-col-bottom"
              :style="{ backgroundColor: item.backgroundColor }"
              v-for="(item, index) in cardList[1]"
              :key="index"
              @click="handleCardClick(item.text)"
            >
              <div class="">
                <a-icon :type="item.icon" class="fz-70" />
                <p class="fz-20 m-t-16">{{ item.text }}</p>
              </div>
            </div>
          </div>
          <div class="a-flex">
            <div
              class="m-b-24 m-r-24 type-card large"
              :style="{ backgroundColor: item.backgroundColor }"
              v-for="(item, index) in cardList[2]"
              :key="index"
              @click="handleCardClick(item.text)"
            >
              <div class="text-left p-t-16 p-l-16">
                <a-icon :type="item.icon" class="fz-70" />
              </div>
              <p class="fz-20 m-t-30">{{ item.text }}</p>
            </div>
          </div>
        </div>
        <div v-if="current === 1" class="card-wrapper">
          <transition enter-active-class="zoom_in" leave-active-class="zoom-out" mode="out-in">
            <a-upload-dragger
              v-if="$isEmpty(file)"
              style="width: 100%; height: 50%"
              name="file"
              rowKey="uid"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
              :customRequest="uploadFile"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">拖拽或点击选择文件上传</p>
              <div class="ant-upload-hint text-warning">
                <p>1.选择excel文件。</p>
                <p>2.大小不能超过5MB。</p>
                <p>3.当前只支持上传一个文件。</p>
              </div>
            </a-upload-dragger>
            <div v-else class="text-center">
              <viewer-image :src="require('@/assets/fileType/Excel.png')" :lazy="false"></viewer-image>
              <p>文件名称：{{ file.name }}</p>
              <p>文件大小：{{ file.size | formatSize }}</p>
              <p>上传时间：{{ file.lastModifiedDate | moment }}</p>
              <y-button type="warning" @click="file = {}">重新上传</y-button>
              <y-button type="primary" @click="handleStartComparison">开始比对</y-button>
            </div>
          </transition>
        </div>
        <div class="card-wrapper" v-if="current >= 2">
          <mock-progress
            ref="progress"
            :strokeWidth="20"
            :stroke-color="
              isError
                ? '#f5222d'
                : {
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }
            "
            @progress="progress"
          ></mock-progress>
          <div class="a-flex a-row-between text-secondary" style="width: 100%">
            <div v-if="!isError">
              <div v-if="percent < 100">
                <a-icon type="loading"></a-icon>
                <span class="p-l-6">数据比对中，请稍后...</span>
              </div>
              <div v-else-if="percent === 100">数据比对完成</div>
            </div>
            <div v-else>数据比对失败，请重试</div>
            <div v-if="!isError">
              <span v-if="percent < 100">{{ percent }}%</span>
              <a-icon v-else class="text-success" type="check-circle" theme="filled" />
            </div>
            <a-icon v-else class="text-error" type="close-circle" theme="filled" />
          </div>
          <transition enter-active-class="zoom_in">
            <div v-if="current === 3 && !isError" class="m-t-26">
              <y-button type="success" @click="handleDownload" icon="download">比对完成，点击下载比对结果文件</y-button>
              <y-button type="primary" @click="handleRest">重新选择比对类型</y-button>
            </div>
            <y-button v-if="isError" type="danger" @click="handleStartComparison(false)">重新比对</y-button>
          </transition>
        </div>
      </a-card>
    </a-col>
    <a-modal :visible="visibleName" title="任务名称" @cancel="handleFormClose" @ok="handleFormSubmit">
      <a-form :form="form">
        <a-form-item>
          <a-textarea
            v-decorator="['exportName', { rules: [{ required: true, message: '请输入任务名称' }] }]"
            placeholder="请输入任务名称"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-form-item v-show="showSelect">
          <a-select
            allowClear
            placeholder="请选择比对字段"
            :options="infoOptions"
            optionFilterProp="children"
            mode="multiple"
            v-decorator="['exportInfo', { rules: [{ required: showSelect, message: '请选择比对字段' }] }]"
          >
            <div slot="dropdownRender" slot-scope="menu">
              <v-nodes :vnodes="menu" />
              <a-divider class="m-y-4" />
              <div
                style="cursor: pointer"
                class="text-center p-y-4 text-primary"
                @mousedown="(e) => e.preventDefault()"
                @click="handleChooseAll"
              >
                全选
              </div>
            </div>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-row>
</template>

<script>
import { limitFileSzie, bytesToSize, downloadEvt } from '@/utils/util'
import { postFiles, beginExport } from '@/api/dataComparison'
import { viewerImage } from '@/components'
import mockProgress from './mockProgress.vue'
import BigNumber from 'bignumber.js'
export default {
  props: {},
  components: {
    viewerImage,
    mockProgress,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  computed: {
    showSelect () {
      return ['公租房信息比对', '保障成员比对', '保障家庭比对'].includes(this.params.exportCategory)
    },
    infoOptions () {
      if (this.$isEmpty(this.params.exportCategory)) {
        return []
      } else {
        const optionsMap = new Map([
          ['公租房信息比对', 'publicHouse'],
          ['保障成员比对', 'personOptions'],
          ['保障家庭比对', 'familyOptions']
        ])
        return this[optionsMap.get(this.params.exportCategory)]
      }
    }
  },
  filters: {
    formatSize: bytesToSize
  },
  data () {
    return {
      current: 0,
      visibleName: false,
      form: this.$form.createForm(this, { name: 'multipleDataComparison' }),
      cardList: [
        [
          {
            icon: 'home',
            text: '现售备案房产信息比对',
            backgroundColor: '#20815D'
          },
          {
            icon: 'home',
            text: '公租房信息比对',
            backgroundColor: '#8AB32D'
          }
        ],
        [
          {
            icon: 'banjichengyuan',
            text: '保障成员比对',
            backgroundColor: '#2478f2'
          },
          {
            icon: 'minzhengtubiao1-24',
            text: '婚姻比对',
            backgroundColor: '#e72c2f'
          },
          {
            icon: 'jiatingguanli',
            text: '保障家庭比对',
            backgroundColor: '#2478f2'
          }
        ],
        [
          {
            icon: 'home',
            text: '商品房信息比对',
            backgroundColor: '#5EC298'
          },
          {
            icon: 'home',
            text: '预售备案房产信息比对',
            backgroundColor: '#259238'
          }
        ]
      ],
      params: {
        file: null,
        exportName: '',
        exportUserID: this.$store.getters.userid,
        exportInfo: '',
        exportCategory: ''
      },
      // 保障家庭比对
      familyOptions: [
        { value: 'ApplyNO', label: '申请编号' },
        { value: 'RegionNo', label: '区级编号' },
        { value: 'TownshipNo', label: '社区编号' },
        { value: 'StrDegress', label: '家庭（辈）' },
        { value: 'CityVfyNumber', label: '市级核定保障人数' },
        { value: 'CityVfyAreaPer', label: '市级核定人均面积' },
        { value: 'StrLiveHousingArea', label: '房屋总建筑面积' },
        { value: 'ApplyClassCategory', label: '申请家庭类型' },
        { value: 'ApplyClass', label: '申请家庭类别(保障方式)' },
        { value: 'CityVfyAssign', label: '保障方式(补贴方式) ' },
        { value: 'ClassName', label: '备案类型（保障方式备注）' },
        { value: 'CityVfyAssignRemark', label: '实物安置备注(补贴方式备注)' },
        { value: 'CityVfyIncome', label: '市级核定人均收入' },
        { value: 'HousCategory', label: '现住房性质' },
        { value: 'SMoney', label: '补贴金额' },
        { value: 'SVarConst', label: '补贴常数' },
        { value: 'SVarNumber', label: '补贴人数' },
        { value: 'SVarArea', label: '补贴面积' },
        { value: 'SVarMonth', label: '补贴月数' },
        { value: 'SVarPercent', label: '补贴系数' },
        { value: 'Proposer', label: '姓名' },
        { value: 'IDCard', label: '身份证号' },
        { value: 'Maritalsta', label: '婚姻状况' },
        { value: 'WorkUnit', label: '工作单位' },
        { value: 'Profession', label: '职业' },
        { value: 'Phone', label: '联系电话' },
        { value: 'LiveAddress', label: '居住详细地址' },
        { value: 'IfDisability', label: '是否残疾' },
        { value: 'ApplyType', label: '户籍类型' },
        { value: 'CensusRegAddress', label: '户籍详细地址' },
        { value: 'ESetDate', label: '安置时间' },
        { value: 'ESitesSelect', label: '安置点' },
        { value: 'CityRfyResult', label: '审批结果' },
        { value: 'CityRfyDate', label: '审批时间' },
        { value: 'AlterType', label: '异动类型' },
        { value: 'AlterInfo', label: '异动原因' },
        { value: 'AlterReason', label: '异动类别' },
        { value: 'AlterDate', label: '异动时间' },
        { value: 'AlterExecutor', label: '异动人' },
        { value: 'IfQueue', label: '确认情况' }
      ],
      // 保障成员
      personOptions: [
        { value: 'ApplyNO', label: '编号' },
        { value: 'Name', label: '姓名' },
        { value: 'IDCards', label: '身份证号' },
        { value: 'Sexs', label: '性别' },
        { value: 'Birthdays', label: '出生日期' },
        { value: 'Nations', label: '民族' },
        { value: 'Relation', label: '关系' },
        { value: 'College', label: '文化程度' },
        { value: 'Maritalstas', label: '婚姻状况' },
        { value: 'WorkUnits', label: '工作单位' },
        { value: 'Profession', label: '职业' },
        { value: 'Phones', label: '联系电话' },
        { value: 'Employment', label: '就业情况' },
        { value: 'LiveDistrictAddress', label: '居住地所在区' },
        { value: 'LiveAddresss', label: '居住详细地址' },
        { value: 'IfDisabilitys', label: '是否残疾' },
        { value: 'DisabilityTypes', label: '残疾类别' },
        { value: 'DisabilityLevels', label: '残疾等级' },
        { value: 'ApplyTypes', label: '户籍类型' },
        { value: 'IfRangeLowObject', label: '居住证号' },
        { value: 'SecurityNos', label: '社保证号或完税证明' },
        { value: 'ProvinceAddress', label: '户籍省' },
        { value: 'CityAddress', label: '户籍市' },
        { value: 'DistrictAddress', label: '户籍县（区）' },
        { value: 'CensusRegAddresss', label: '户籍详细地址' },
        { value: 'GroupOfApplicants', label: '申请人所属群体' },
        { value: 'IfLowObjects', label: '收入认定' },
        { value: 'LowObjectNOs', label: '低保证号' }
      ],
      // 公租房比对
      publicHouse: [
        { value: '安置点', label: '安置点' },
        { value: '计划', label: '计划' },
        { value: '项目', label: '项目' },
        { value: '地址', label: '地址' },
        { value: '栋', label: '栋' },
        { value: '单元', label: '单元' },
        { value: '楼层', label: '楼层' },
        { value: '附号', label: '附号' },
        { value: '面积', label: '面积' },
        { value: '结构', label: '结构' },
        { value: '状态', label: '状态' },
        { value: '房源代码', label: '房源代码' },
        { value: '姓名', label: '姓名' },
        { value: '身份证号', label: '身份证号' },
        { value: '申请编号', label: '申请编号' },
        { value: '审批结果', label: '审批结果' },
        { value: '审批日期', label: '审批日期' },
        { value: '备注', label: '备注' },
        { value: '房屋性质', label: '房屋性质' }
      ],
      // 上传
      file: {},
      percent: 0,
      isError: false,
      successPath: ''
    }
  },
  methods: {
    uploadFile (options) {
      // eslint-disable-next-line prefer-const
      let { exportInfo, exportName } = this.form.getFieldsValue()
      if (Array.isArray(exportInfo)) {
        exportInfo = exportInfo.join(',')
      } else {
        exportInfo = ''
      }
      postFiles(
        Object.assign({}, this.params, {
          exportInfo,
          exportName,
          file: options.file
        })
      )
        .then((res) => {
          const { state, msg } = res[0]
          if (state === '1') {
            options.onSuccess(res[0], options.file)
          } else {
            this.$message.error(msg || '文件上传失败，请重试！')
            options.onError(new Error(msg || '文件上传失败，请重试！'))
          }
        })
        .catch(options.onError)
    },
    handleCardClick (type) {
      this.visibleName = true
      this.params.exportCategory = type
    },
    handleFormClose () {
      this.visibleName = false
      this.params.exportCategory = ''
      this.form.resetFields()
    },
    handleChooseAll () {
      this.form.setFieldsValue({
        exportInfo: this.infoOptions.map((e) => e.value)
      })
    },
    handleFormSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.params.exportName = values.exportName
          this.current++
          this.visibleName = false
        }
      })
    },
    beforeUpload (file) {
      const fileType = file.name.split('.').pop()
      if (['xls', 'xlsx'].indexOf(fileType.toLowerCase()) === -1) {
        this.$message.warning('只能上传.XLS.XLSX格式的文件!')
        return false
      } else {
        if (limitFileSzie(file.size, '5MB')) {
          return true
        } else {
          this.$message.warning('最大只能上传5MB大小的文件!')
          return false
        }
      }
    },
    handleChange ({ file, fileList }) {
      if (file.status === 'done') {
        const $file = fileList.pop()
        if ($file.response) {
          $file.url = $file.response.Path
        }
        this.file = $file
      }
    },
    handleStartComparison (next = true) {
      if (next) {
        this.current++
      }
      this.isError = false
      this.$nextTick(() => {
        this.$refs.progress.start()
        beginExport({ exportName: this.form.getFieldValue('exportName') })
          .then((res) => {
            const { state, FilePaht, msg } = res
            if (state === '200') {
              this.$refs.progress.done(true)
              this.current = 3
              this.successPath = FilePaht
            } else {
              this.$message.error(msg || '数据比对失败，请重试！')
              this.$refs.progress.done(0)
              this.percent = 0
              this.isError = true
            }
          })
          .catch(() => {
            this.$refs.progress.done(0)
            this.percent = 0
            this.isError = true
          })
      })
    },
    progress (n) {
      if (n === 1) {
        setTimeout(() => {
          this.percent = 100
        }, 100)
      } else {
        this.percent = new BigNumber(n).dp(2).multipliedBy(100).toNumber()
      }
    },
    handleDownload () {
      const start = this.successPath.lastIndexOf('/')
      const end = this.successPath.lastIndexOf('.')
      const url = this.successPath.replaceAll('~', process.env.VUE_APP_API_BASE_URL)
      downloadEvt(url, this.successPath.substring(start + 1, end))
    },
    handleRest () {
      this.$emit('reset')
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-card {
  height: 100%;
  .ant-card-body {
    height: 100%;
    overflow-x: hidden;
    .card-wrapper {
      width: 100%;
      height: 100%;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: center;
    }
  }
}
/deep/ .ant-steps-item:not(:last-child) {
  height: 200px;
}
.type-card-list {
  height: 100%;
  .type-card {
    text-align: center;
    border-radius: 24px;
    color: #fff;
    padding: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    p {
      font-weight: 700;
      letter-spacing: 4px;
    }
  }
  .large {
    width: 350px;
    height: 220px;
  }
  .default {
    width: 222px;
    height: 220px;
  }
}
</style>
